/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.socket.server.netty;

import java.io.FileInputStream;

import org.apache.commons.jelly.JellyContext;
import org.apache.commons.jelly.Script;
import org.apache.commons.jelly.XMLOutput;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ChildChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;

/**
 * DOCME
 * 
 * @author Nick.Tan
 */
@ChannelPipelineCoverage("all")
public class DefaultChannelHandler extends BaseChannelHandler {

	private static final Logger logger = LoggerFactory.getLogger(DefaultChannelHandler.class);

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		ChannelBuffer buffer = (ChannelBuffer) e.getMessage();

		JellyContext context = new JellyContext();
		String stringData = buffer.toString("UTF-8");
		context.setVariable("stringData", stringData);

		String scriptLocation = getConfigurationBean().getScriptLocation();
		InputSource input = new InputSource(new FileInputStream(scriptLocation));
		Script script = context.compileScript(input);
		XMLOutput output = XMLOutput.createDummyXMLOutput();
		script.run(context, output);

		Object response = context.getVariable("response");
		if (response != null) {
			String resStr = response.toString();
			byte[] byResp = resStr.getBytes("UTF-8");
			ChannelBuffer out = ChannelBuffers.buffer(byResp.length);
			out.writeBytes(byResp);
			e.getChannel().write(out);
		}
	}

	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		super.channelClosed(ctx, e);
		logger.info(">>>>> status: channelClosed: " + ctx.getChannel().getRemoteAddress());
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		super.channelConnected(ctx, e);
		logger.info(">>>>> status: channelConnected: " + ctx.getChannel().getRemoteAddress());
	}

	@Override
	public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		super.channelDisconnected(ctx, e);
		logger.info(">>>>> status: channelDisconnected: " + ctx.getChannel().getRemoteAddress());
	}

	@Override
	public void childChannelClosed(ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception {
		super.childChannelClosed(ctx, e);
		logger.info(">>>>> status: childChannelClosed: " + ctx.getChannel().getRemoteAddress());
	}
}
